package com.cbw.firegame.member.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cbw.common.utils.R;
import com.cbw.common.vo.MemberEntity;
import com.cbw.firegame.member.feign.ThirdpartyFeignService;
import com.cbw.firegame.member.service.MemberService;
import com.cbw.firegame.member.vo.RegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class RegisterController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThirdpartyFeignService thirdpartyFeignService;

    @Autowired
    MemberService memberService;


//    @RequestMapping("/register")
//    public String register(){
//        return "register";
//    }
//    @PostMapping("/registPost")
//    public String registPost(){
//        return "register";
//    }
    @ResponseBody
    @RequestMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone")String phone){

        String redisCode = redisTemplate.opsForValue().get("register:code" + phone);
        if (!StringUtils.isEmpty(redisCode)){
            Long redisTime =Long.parseLong(redisCode.split("_")[1]) ;
            if (System.currentTimeMillis()-redisTime>60000){
                return R.error("验证码频率过高，请稍后再试");
            }
        }
        String code= UUID.randomUUID().toString().substring(0,5);
        String rediscode= code +"_"+ System.currentTimeMillis();
//        缓存验证码
        redisTemplate.opsForValue().set("register:code"+phone,rediscode,5, TimeUnit.MINUTES);
        System.out.println(phone+"---------"+code);
        thirdpartyFeignService.sendCode(phone,code);

        return  R.ok();
    }
@PostMapping("/regist")
public String regist(@Valid RegistVo registVo, BindingResult result, RedirectAttributes redirectAttributes){
    if (result.hasErrors()){
            Map<String, String> errors =result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage,(v1,v2)->{
                     return v1;
                    }));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:9100/register";
        }


    int username = memberService.count(new QueryWrapper<MemberEntity>().eq("username", registVo.getUsername()));
    System.out.println(registVo.getUsername());
    if (username==0){
        String code = registVo.getYzm();
        String s = redisTemplate.opsForValue().get("register:code" + registVo.getPhone());
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                redisTemplate.delete("register:code" + registVo.getPhone());
                R r= memberService.regist(registVo);
                if (r.getCode()==0){
                    //成功

                    return "redirect:http://localhost:9100/login";
                }else{
                    redirectAttributes.addFlashAttribute("msg","用户名或手机已经被注册");
                    return "redirect:http://localhost:9100/register";
                }

            }else{
                Map<String, String> errors =new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //效验出错回到注册页面
                return "redirect:http://localhost:9100/register";

            }
        }else {
            redirectAttributes.addFlashAttribute("msg","验证码错误");
            return "redirect:http://localhost:9100/register";
        }

    }else {
        redirectAttributes.addFlashAttribute("msg","用户名或手机已经被注册");
        return "redirect:http://localhost:9100/register";
    }





    }

}
